package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dot.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2021-11-02
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult<WmChannel> listByName(ChannelDto dto) {
        //根据名称查询
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //使用mybatisplus推荐的lamda表达式的写法
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //判断传过来的参数唯一非空
        if (StringUtils.isNoneBlank(dto.getName())) {
            //构建name模糊查询
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //构建分页对象
        IPage<WmChannel> page = new Page<WmChannel>(dto.getPage(), dto.getSize());
        //返回查询结果
        IPage<WmChannel> page1 = this.page(page, queryWrapper);
        //构建分页结果对象
        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel channel) {
        //1、channel不能为空
        if (channel == null || StringUtils.isBlank(channel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、频道名称不能重复
        //先根据传过来的名称查询。如果表中没有那么直接保存，如果有返回一个消息
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, channel.getName());

        WmChannel one = this.getOne(queryWrapper);
        if (one == null) { //表中没有这样的数据 是可以新增的
            channel.setCreatedTime(new Date());
            this.save(channel);
            return ResponseResult.okResult();
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);//数据已存在
    }

}